# -*- coding: utf-8 -*-
import dbo, sys
from string import Template
from web.db import sqlquote
from objects.directory import Directory

def _parse_hierarchy(paths):
    """
    Распарсивает иерархию на join'ы

    @param list paths
    @return list
    """
    vars = {}
    left_joins = []
    dir_no = 0
    for path in paths:
        dir_no += 1
        if path.isdigit(): param = 'id'
        else: param = 'name'
        tpl = '\tLEFT JOIN directories AS dir${dir_no} ON dir${dir_no}.' + param + ' = ' + sqlquote(path) + ' AND dir${dir_no}.parent = dir${dir_parent}.id'
        left_joins.append(Template(str(tpl)).substitute(dir_no=dir_no, dir_parent=dir_no-1))

    # Выбираем результат из последней в иерархии директории
    left_joins.append(Template('\tLEFT JOIN directories AS dir${dir_no}'\
        ' ON dir${dir_no}.parent = dir${dir_parent}.id')\
        .substitute(dir_no=dir_no+1, dir_parent=dir_no))

    return (left_joins, vars, dir_no)

def _search_by_hierarchy(hierarchy):
    (left_joins, vars, dir_no) = _parse_hierarchy(hierarchy[1:])

    vars['root_dir'] = hierarchy[0]
    if hierarchy[0].isdigit(): root_dir_param = 'id'
    else: root_dir_param = 'name'

    # Собираем запрос
    cols = []
    for key in ('id', 'type', 'parent', 'name', ):
        cols.append('dir' + str(dir_no) + '.' + key + ' AS r_' + key + ', '\
                    'dir' + str(dir_no+1) + '.' + key)

    query = 'SELECT ' + ', '.join(cols) + \
      ' FROM directories AS dir0\n' + \
      '\n'.join(left_joins) + \
      '\nWHERE dir0.' + root_dir_param + ' = ' + sqlquote(vars['root_dir']) + ' AND dir0.parent = 0'

    print str(query)

    # Выполняем запрос
    db = dbo.get_cursor()
    db.execute(str(query))

    tables = ('root_dir', 'dir_contents')
    result = {}

    row_data = {}

    for row in db:
        if row is None:
            break
        num = 0
        for column in db.description:
            column = column[0]
            # fucking hack
            if column.startswith('r_'):
                table = tables[0]
                column = column[2:]
            else: table = tables[1]
            #table = tables[column[6]]

            if table not in result:
                result[table] = []
            if table not in row_data:
                row_data[table] = {}

            row_data[table][column] = row[num]
            num += 1

        for (key, value) in row_data.iteritems():
            result[key].append(value)

        row_data = {}

    return result

def _get_root_contents():
    """
    Возвращает директории с parent=0

    @return list
    """
    db = dbo.get_conn()
    return db.query('SELECT root_dir.* FROM directories root_dir WHERE root_dir.parent = 0')

def get_by_hierarchical_path(hierarchy):
    """
    Возвращает содержимое директории по указанному пути

    @param string hierarchy
    @return list Список потомков Entity (File и Directory)
    """
    hierarchy = filter(lambda item: len(item.strip()) != 0, hierarchy.split('/')) # Удаляем пустые элементы из пути

    dir_items = []
    if not hierarchy:
        results = _get_root_contents()
        root_dir = Directory()
    else:
        results = _search_by_hierarchy(hierarchy)
        if 'root_dir' not in results \
            or results['root_dir'] is None \
            or results['root_dir'][0]['id'] is None:
            return None

        root_dir = Directory(results['root_dir'][0])
        results = results['dir_contents']

    if not results:
        return None

    for result in results:
        # Поддиректории
        if result['type'] == 'directory':
            dir_items.append(Directory(result.copy()))

    return { 'directory' : root_dir, 'content' : dir_items }
